#$Id: tags.py 32976 2008-09-04 03:37:39Z jorwen@NETEASE.COM $

from django import template
from v4a.models import Vote, VotesLog

register = template.Library()

class CaseTagsNode(template.Node):

	def __init__(self, val, val_list, nodelist):
		self.val = template.Variable(val)
		self.val_list = val_list
		self.nodelist = nodelist

	def __repr__(self):
		return "<CaseNode>"

	def render(self, context):
		self.val = self.val.resolve(context)
		idx = 0
		for v in self.val_list:
			self.val_list[idx] = template.Variable(v).resolve(context)
			idx += 1

		if self.val in self.val_list:
			return self.nodelist.render(context)
		else:
			return ''


class VoteLogContertNode(template.Node):

	def __init__(self, log_set, vote, new_log_name):
		self._log_set = log_set
		self._vote = vote
		self._new_log_name = new_log_name

	def render(self, context):
		self._log_set = template.Variable(self._log_set).resolve(context) 
		self._vote = template.Variable(self._vote).resolve(context) 
		context[self._new_log_name] = VotesLog.objects.logs_convert(self._log_set, self._vote)	
		return ''


def do_case(parser, token):
	'''
		{% case a in 1 2 3 %}
			... ...
		{% endcase %}
	'''
	bits = token.split_contents()
	if len(bits) < 4:
		raise template.TemplateSyntaxError("'%s' tag takes more than four arguments")

	if bits[2] != 'in':
		raise template.TemplateSyntaxError("second argument to '%s' tag must be 'in'")

	end_tag = 'end' + bits[0]
	nodelist = parser.parse((end_tag, ))
	parser.delete_first_token()
	return CaseTagsNode(bits[1], bits[3:], nodelist)


def do_votelog_contert(parser, token):
	'''
		{% log_convert logs by vote as new_log %}
	'''
	bits = token.split_contents()
	if len(bits) != 6:
		raise template.TemplateSyntaxError("'%s' tag takes four arguments")

	if bits[2] != 'by':
		raise template.TemplateSyntaxError("second argument to '%s' tag must be 'by'")

	if bits[4] != 'as':
		raise template.TemplateSyntaxError("forth argument to '%s' tag must be 'as'")


	return VoteLogContertNode(bits[1], bits[3], bits[5])


register.tag('case', do_case)
register.tag('log_convert', do_votelog_contert)
